<?php
/**
 * Created by PhpStorm.
 * User: gyq
 * Date: 2018/11/27
 * Time: 20:44
 */

namespace app\api\service;

use app\api\model\Order as OrderModel;
use app\api\model\Product;
use app\api\service\Order as OrderService;
use app\lib\enum\OrderStatusEnum;
use think\Db;
use think\Exception;
use think\facade\Env;
use think\facade\Log;

include Env::get('root_path') . 'extend/wxPay/WxPay.Api.php';

class WxNotify extends \WxPayNotify
{
    public function NotifyProcess($objData, $config, &$msg)
    {
        if ($objData['result_code'] == 'SUCCESS') {
            $orderNo = $objData['out_trade_no'];
            Db::startTrans();
            try {
                $order = OrderModel::where('order_no', 'eq', $orderNo)->find();
                if ($order->status == 1) {
                    $orderService = new OrderService();
                    $stockStatus = $orderService->checkOrderStock($order->id);
                    if ($stockStatus['pass']) {
                        $this->updateOrderStatus($order->id, true);
                        $this->reduceStock($stockStatus['pStatusArray']);
                    } else {
                        $this->updateOrderStatus($order->id, false);
                    }
                }
                Db::commit();
                return true;
            } catch (Exception $ex) {
                Db::rollback();
                Log::error($ex);
                return false;
            }
        }    else {
            return true;
        }
    }

//    更新订单状态
    private function updateOrderStatus($orderId, $success)
    {
        $orderStatus = $success ? OrderStatusEnum::PAID : OrderStatusEnum::PAID_BUT_OUT_OF;
        $order = OrderModel::where('id', 'eq', $orderId)->find();
        $order->status = $orderStatus;
        $order->save();
    }

//    减库存
    private function reduceStock($pStatusArray)
    {
        foreach ($pStatusArray as $singleStatus) {
            Product::where('id', 'eq', $singleStatus['id'])->setDec('count', $pStatusArray['count']);
        }
    }
}